import numpy as np

from util.util_ris_pattern_2 import point_2_phi_pattern, phase_2_bit, phase_2_pattern, phase_2_pattern_xyz_fft, \
    phase_2_pattern_xyz, eps, phaseBit_2_deg

from util.util_analysis_plane import get_peaks, get_peak_nth


def get_psll(patternBit, beam_num):
    psll = 0
    # pattern 转dB
    pattern_dbw = 20 * np.log10(np.abs(patternBit) / np.max(np.max(np.abs(patternBit))) + eps)
    # pattern找峰值
    peaks = get_peaks(pattern_dbw)
    # 找beam+1峰作为 PSLL
    peak_2nd = get_peak_nth(peaks, beam_num)
    if peak_2nd is not None:
        psll = peak_2nd[0]
    return psll


def get_psll_by_phaseRad(phaseRad, beam_num):
    # patternBit = phase_2_pattern(phaseRad)                # 公式法直接计算, 准确但速度太慢
    patternBit, x, y = phase_2_pattern_xyz_fft(phaseRad)  # FFT法计算, 快速
    # 计算码阵的最大副瓣
    psll = get_psll(patternBit, beam_num)
    return psll


def get_psll_by_phaseDeg(phaseBitDeg, beam_num):
    # 角度转弧度
    phaseRad = np.deg2rad(phaseBitDeg)
    return get_psll_by_phaseRad(phaseRad, beam_num)


def get_psll_by_phase(phase, bit_num, beam_num):
    # 相位转换 X bit
    phaseBit, phaseBitDeg = phase_2_bit(phase, bit_num)
    # 计算phase_mix的方向图
    return get_psll_by_phaseBit(phaseBit, bit_num, beam_num)

def get_psll_by_phaseBit(phaseBit, bit_num, beam_num):
    # 比特转角度
    phaseBitDeg = phaseBit_2_deg(phaseBit, bit_num)
    return get_psll_by_phaseDeg(phaseBitDeg, beam_num)